<template>
	<view
		:id="id"
		:style="{
			width: '100%!improtant',
			height: height + 'px',
			position: 'relative'
		}"
		:class="['uni-image', type]"
	>
		<img :src="src" />
	</view>
</template>

<script>
export default {
	props: {
		src: { type: String, default: '' }
	},
	data() {
		return {
			type: 'horizontal',
			id: 'image_' + this.getUUID(8),
			width: 0,
			height: 0,
			path: ''
		};
	},
	watch: {
		src: {
			handler(value) {
				if(value) {
					this.path = value;
					this.$nextTick(() => {
						this.calc(value);
					});
				}
			},
			immediate: true
		}
	},
	methods: {
		getImageInfo(url) {
			return new Promise(resolve => {
				uni.getImageInfo({
					src: url,
					success(res) {
						const { path, width, height } = res;
						resolve({ base64: path, width, height });
					},
					fail(res) {
						resolve({});
					}
				});
			});
		},
		getUUID(len, radix) {
			var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
			var uuid = [],
				i;
			radix = radix || chars.length;
			if (len) {
				for (i = 0; i < len; i++) uuid[i] = chars[0 | (Math.random() * radix)];
			} else {
				var r;
				uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
				uuid[14] = '4';
				for (i = 0; i < 36; i++) {
					if (!uuid[i]) {
						r = 0 | (Math.random() * 16);
						uuid[i] = chars[i == 19 ? (r & 0x3) | 0x8 : r];
					}
				}
			}
			return uuid.join('');
		},
		getContainerInfo() {
			return new Promise(resolve => {
				const query = uni.createSelectorQuery().in(this);
				query
					.select('#' + this.id)
					.boundingClientRect(rect => {
						resolve(rect);
					})
					.exec();
			});
		},
		async calc(src) {
			const rect = await this.getContainerInfo();
			const image = await this.getImageInfo(src);
			// this.path = image.base64;
			if (image.width <= image.height) {
				this.type = 'vertical';
				this.height = Math.ceil(rect.width / (670 / 890));
			} else {
				this.type = 'horizontal';
				this.height = Math.ceil(rect.width / (670 / 447));
			}
		}
	}
};
</script>

<style lang="less" scoped>
.uni-image {
	img {
		-webkit-touch-callout: none;
		-webkit-user-select: none;
		-moz-user-select: none;
		display: block;
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		right: 0;
		bottom: 0;
	}
}
</style>
